#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <stdio.h>
#include<string.h>
using namespace std;

class UdpClient
{
public:
    UdpClient(int port, string ip)
        : _serverport(port), _serverIP(ip)
    {
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);

        if (_sockfd < 0)
        {
            cout << "client socket error" << endl;
            return;
        }
        else
        {
            cout << "client socket success" << endl;
        }
    }
    void Run()
    {
        string msg;
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_serverport);
        peer.sin_addr.s_addr = inet_addr(_serverIP.c_str());

        while (true)
        {
            cout << "Please input: " ;
            getline(cin, msg);
            ssize_t size = sendto(_sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)(&peer), sizeof(peer));
            if(size==-1)
            {
                cerr<<"sendto error"<<endl;
                return;
            }
            cout<<msg<<endl;
        }
    }
    ~UdpClient()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;      // 网络文件描述符
    int _serverport;  // 服务器进程的端口号
    string _serverIP; // 服务器的IP地址
};